package 
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.system.System;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.utils.getTimer;
	
	/**
	 * 
	 * @author Zachary
	 * 
	 */
	public class FpsMonitor extends Sprite
	{
		private var last:uint = getTimer();
		private var ticks:uint = 0;
		private var tf:TextField=null;
		private var tfColor:uint=0;
		private var preFps:Number=-1;
		
		/**
		 * FPS监测器
		 * @param xPos
		 * @param yPos
		 * @param color
		 * @param fillBackground
		 * @param backgroundColor
		 * 
		 */
		public function FpsMonitor(xPos:int=0, yPos:int=0, color:uint=0x000000,
								   fillBackground:Boolean=false, backgroundColor:uint=0xffffff) 
		{
			x = xPos;
			y = yPos;
			tf = new TextField();
			tf.textColor = color;
			this.tfColor=color;
			tf.text = "----- fps";
			tf.selectable = false;
			tf.background = fillBackground;
			tf.backgroundColor = backgroundColor;
			tf.autoSize = TextFieldAutoSize.LEFT;
			addChild(tf);
			width = tf.textWidth;
			height = tf.textHeight;
			addEventListener(Event.ENTER_FRAME, tick);
		}
		
		/**
		 * 单位操作 
		 * @param evt
		 * 
		 */
		public function tick(evt:Event):void
		{
			ticks++;
			var now:uint = getTimer();
			var delta:uint = now - last;
			if (delta >= 1000) 
			{
				var fps:Number = ticks / delta * 1000;
				if(preFps!=-1&&Math.abs(fps-preFps)>3)
				{
					tf.textColor=0x00FFFF;
					tf.text = fps.toFixed(1) + " fps,"+ Math.round(System.totalMemory/1024)/1024+'Mb';
				}
				else
				{
					tf.textColor=tfColor;
					tf.text = fps.toFixed(1) + " fps,"+ Math.round(System.totalMemory/1024)/1024+'Mb';
				}
				ticks = 0;
				last = now;
			}
		}
	}
}